package fr.enssat.tpcloud.dao;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import fr.enssat.tpcloud.model.Post;
import fr.enssat.tpcloud.model.User;

/**
 * DAO Hibernate permettant la gestion des tuple User pour une BdD derby
 * Hibernate DAO for User.
 * 
 */
public class UserDao extends HibernateDaoSupport {


    /**
     * Get all user.
     * 
     * @return collection of user
     */
    @SuppressWarnings("unchecked")
    public Collection<User> getAllUser() {
        return getHibernateTemplate().loadAll(User.class);
    }

    /**
     * Save a new User.
     * 
     * @param user user to save
     */
    public void save(User user) {
           getHibernateTemplate().save(user);
    }

    /**
     * Delete a User.
     * 
     * @param user user to delete
     */
    public void delete(User user) {
        getHibernateTemplate().delete(user);
    }

    /**
     * Find a user with this email.
     * 
     * @param email user email
     * @return user with this email or null
     */
    @SuppressWarnings("unchecked")
    public User findByEmail(String email) {
        
    	// Critere pour trouver le user
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class)
            .add(Restrictions.eq("email", email));
        
        List<User> allResult = getHibernateTemplate().findByCriteria(criteria);
        
        // Retourne null s'il y a plusieurs user avec le mm mail et le user sinon
        User result = null;
        if(allResult.size() == 1) {
            result = allResult.get(0);
        }

        return result;
    }
    
    @SuppressWarnings("unchecked")
    public int nbPostSince(User user, Date startDate){
    	
    	// Recuperation des posts appartenant a user depuis la date startDate
        DetachedCriteria criteria = DetachedCriteria.forClass(Post.class)
            .add(Restrictions.and(Restrictions.eq("user", user),
            		Restrictions.ge("creationDate", startDate)));
        
        // Comptage des posts
        criteria.setProjection(Projections.rowCount());
        
        List<Integer> allResult = getHibernateTemplate().findByCriteria(criteria);
        
        // Retour du nombre de post
        int result = 0;
        if(allResult.size() == 1){
        	result = allResult.get(0);
        }
        return result;
    }

}
